<template>
  <el-card class="el-card--has-heading success">
    <div slot="header" class="v-card__headerInner">
      <p>生鲜商品分类</p>
      <transition name="el-zoom-in-center">
        <div v-show="showTip">
          <p class="v-card__header-tip">单击图片可预览大图</p>
        </div>
      </transition>
      <el-button
        class="v-card__headerAction"
        type="text"
        @click="onClickCreate"
        v-auth:[$P.business.freshCategory.create]
      >创建分类</el-button>
    </div>
    <v-table
      :dataSource="dataSource"
      :columns="filterColumn(columns,[$P.business.freshCategory.update, $P.business.freshCategory.delete])"
      :loading="loading"
      :total="total"
      v-bind="bindProps"
      v-on="bindListeners"
    >
      <template slot="toolbar">
        <el-form inline size="small" :model="query" ref="query" class="flex flex-wrap">
          <el-form-item prop="classifyName">
            <el-input placeholder="请输入分类名称" v-model.trim="query.classifyName" />
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="handleSearch">查询</el-button>
            <el-button type="warning" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </template>
    </v-table>

    <Modal
      :title="modalTitle"
      :loading="modalLoading"
      :visible.sync="visible"
      :width="$V.size.sm"
      :onOk="handleSubmit"
      :onCancel="handleClose"
      :okText="modalType === 'create' ? $t('createText') : $t('updateText')"
    >
      <FreshCategoryForm :record="record" ref="form" />
    </Modal>
  </el-card>
</template>

<script>
import {
  getFreshCategoryList,
  createFreshCategory,
  updateFreshCategory,
  deleteFreshCategory,
  showFreshCategoryInHome,
  offShowFreshCategoryInHome
} from '@/api'

/* components
---------------------------------------------------------------- */
import FreshCategoryForm from './components/FreshCategoryForm'
import { Query } from '@/mixins'

/* model
---------------------------------------------------------------- */
import { primaryKey } from './model'

export default {
  mixins: [Query('query')],

  data () {
    return {
      showTip: false,
      total: 0,
      dataSource: [],
      loading: false,
      columns: [
        { prop: 'classifyName', label: '分类名称' },
        { prop: 'classifySummary', label: '分类简介' },
        {
          prop: 'classifyIcon',
          label: '分类icon',
          formatter: (row) => {
            const imgSrc = this.$V.staticBaseURL + row['classifyIcon']
            return (
              <el-image
                class="row-img"
                src={imgSrc}
                preview-src-list={[imgSrc]}
              ></el-image>
            )
          }
        },
        {
          prop: 'classifyImage',
          label: '分类图片',
          formatter: (row) => {
            const imgSrc = this.$V.staticBaseURL + row['classifyImage']
            return (
              <el-image
                class="row-img"
                src={imgSrc}
                preview-src-list={[imgSrc]}
              ></el-image>
            )
          }
        },
        {
          prop: 'classifyShowHome',
          label: '首页展示',
          minWidth: this.$V.cellSize.logic,
          formatter: (row) => {
            return (
              <el-link
                type={row.classifyShowHome ? 'primary' : 'danger'}
                onClick={() =>
                  this.toggleShowInHome(!row.classifyShowHome, row)
                }
              >
                {row.classifyShowHome ? '是' : '否'}
              </el-link>
            )
          }
        },
        {
          prop: 'classifyCreateTime',
          label: '创建时间',
          width: this.$V.cellSize.date,
          formatter: (row) => this.$formatTime(row['classifyCreateTime'])
        },
        { prop: 'classifyCreateUserName', label: '创建人' },
        {
          prop: 'classifyUpdateTime',
          label: '修改时间',
          width: this.$V.cellSize.date,
          formatter: (row) => this.$formatTime(row['classifyUpdateTime'])
        },
        { prop: 'classifyUpdateUserName', label: '修改人' },
        {
          label: '操作',
          minWidth: this.$V.cellSize.action,

          formatter: this.getActionDecorator([
            {
              icon: 'el-icon-edit',
              action: this.onClickUpdate,
              type: 'primary',
              auth: this.$P.business.freshCategory.update
            },
            {
              icon: 'el-icon-delete',
              action: this.onClickDelete,
              type: 'danger',
              auth: this.$P.business.freshCategory.delete
            }
          ])
        }
      ],
      query: {
        classifyName: ''
      },
      record: {},

      // -------- Modal ----------
      visible: false,
      modalLoading: false,
      modalType: ''
      // -------- !Modal ----------
    }
  },
  methods: {
    // Requests
    // ------------------------------------------
    getFreshCategoryList (fn) {
      return this.Catch(getFreshCategoryList, {
        onOk (res) {
          this.dataSource = res.data.data
          this.total = res.data.total
        }
      })('loading', (fn || this.$noop)(this.query))
    },

    deleteFreshCategory (id, { onOk }) {
      return this.Catch(deleteFreshCategory, {
        onOk
      })(null, id)
    },

    createFreshCategory (data) {
      return this.Catch(createFreshCategory, {
        onOk () {
          this.$message.success(this.$t('createOk'))
          this.getFreshCategoryList()
          this.visible = false
        }
      })('modalLoading', data)
    },

    updateFreshCategory (id, data) {
      return this.Catch(updateFreshCategory, {
        onOk () {
          this.$message.success(this.$t('updateOk'))
          this.getFreshCategoryList()
          this.visible = false
        }
      })('modalLoading', id, data)
    },

    showFreshCategoryInHome (id) {
      return this.Catch(showFreshCategoryInHome, {
        onOk () {
          this.$message.success('设置首页展示成功')
          this.getFreshCategoryList()
        }
      })(null, id)
    },
    offShowFreshCategoryInHome (id) {
      return this.Catch(offShowFreshCategoryInHome, {
        onOk () {
          this.$message.success('取消首页展示成功')
          this.getFreshCategoryList()
        }
      })(null, id)
    },
    // Table
    // ------------------------------------------

    onClickDelete (row) {
      this.ConfirmDelete({
        onOk: () =>
          this.deleteFreshCategory(row[primaryKey], {
            onOk () {
              this.$message.success(this.$t('deleteOk'))
              this.getFreshCategoryList()
            }
          })
      })
    },

    onClickUpdate (row) {
      this.modalType = 'update'
      this.record = row
      this.visible = true
    },

    onClickCreate () {
      this.modalType = 'create'
      this.record = {}
      this.visible = true
    },

    toggleShowInHome (willShow, row) {
      this.ConfirmShowInHome({
        show: willShow,
        onOk: () =>
          willShow
            ? this.showFreshCategoryInHome(row[primaryKey])
            : this.offShowFreshCategoryInHome(row[primaryKey])
      })
    },

    // Modal
    // ------------------------------------------
    handleSubmit () {
      this.$refs.form.submit((valid, values) => {
        if (valid) {
          if (this.modalType === 'create') {
            this.createFreshCategory(values)
          } else {
            this.updateFreshCategory(values[primaryKey], values)
          }
        }
      })
    },

    // 关闭modal清理数据
    handleClose () {
      this.visible = false
    }
  },
  computed: {

    modalTitle () {
      return this.modalType === 'create'
        ? this.$t('createText')
        : this.$t('updateText')
    }
  },
  components: { FreshCategoryForm },

  created () {
    this.getFreshCategoryList()
    this.inject(this.getFreshCategoryList)

    this.$nextTick(() => (this.showTip = true))
  }
}
</script>
